/*
 * @description:
 * @Author: lal
 * @Date: 2021-04-25 15:33:47
 * @LastEditors: lal
 * @LastEditTime: 2021-04-26 19:35:22
 */
/*
 * @lc app=leetcode.cn id=2 lang=javascript
 *
 * [2] 两数相加
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
  // [2] 两数相加
  let current = new ListNode()
  let dummy = current
  let carry = 0

  while (l1 !== null || l2 !== null) {
    let sum = 0
    if (l1 !== null) {
      sum += l1.val
      l1 = l1.next
    }
    if (l2 !== null) {
      sum += l2.val
      l2 = l2.next
    }
    sum += carry
    current.next = new ListNode(sum % 10)
    current = current.next
    carry = Math.floor(sum / 10)
  }
  if (carry !== 0) {
    current.next = new ListNode(carry)
  }

  return dummy.next
}
// @lc code=end
